from django import forms
from bug_manage import models
from bug_manage.forms.bootstrap import BootStrapForm
from django.core.exceptions import ValidationError
from utils.tencent import cos

class FolderModelForm(BootStrapForm, forms.ModelForm):
    class Meta:
        model = models.FileRepository
        fields = ['name']

    def __init__(self, request, parent_object, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
        self.parnt_object = parent_object

    def clean_name(self):
        name = self.cleaned_data.get('name')
        # 数据库判断当前目录下此文件夹是否存在
        if self.parnt_object:
            exists = models.FileRepository.objects.filter(file_type=2, name=name, project=self.request.tracer.project,
                                                 parent=self.parnt_object).exists()
        else:
            exists = models.FileRepository.objects.filter(file_type=2, name=name, project=self.request.tracer.project,
                                                 parent__isnull=True).exists()
        if exists:
            raise ValidationError('文件夹已存在')
        return name


class FileModelForm(forms.ModelForm):
    etag = forms.CharField(label='ETag')
    class Meta:
        model = models.FileRepository
        exclude = ['project','file_type','update_user','update_datetime']

    def __init__(self,request,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.request = request

    def clean_file_path(self):
        return "https://{}".format(self.cleaned_data.get('file_path'))

    """文件校验，防止用户不经过cos而直接向数据库伪造post请求"""
    # def clean(self):
    #     key = self.cleaned_data.get('key')
    #     etag = self.cleaned_data.get('etag')
    #     size = self.cleaned_data.get('size')
    #     if not key or not etag:
    #         return self.cleaned_data
    #     # 向cos校验文件是否合法,调用cos SDK校验功能
    #     from qcloud_cos.cos_exception import CosServiceError
    #     try:
    #         result =  cos.check_file(self.request.tracer.project.bucket,self.request.tracer.project.region,key)
    #     except CosServiceError as e:
    #         self.add_error(key,'文件不存在')
    #         return self.cleaned_data
    #     cos_etag = result.get('ETag')
    #     if etag != cos_etag:
    #         self.add_error('etag','ETag错误')
    #     cos_length = result.get('Content_Length')
    #     if int(cos_length) != size:
    #         self.add_error('size', '文件大小错误')
    #
    #     return self.cleaned_data





